package com.thinkgem.jeesite.modules.sys.service;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.product.dao.attribute.TbProductAttributeDao;
import com.thinkgem.jeesite.modules.product.entity.attribute.TbProductAttribute;
import com.thinkgem.jeesite.modules.sys.dao.*;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.utils.UploadDemo;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by WAjava on 2016-10-21.
 */
@Service
@Transactional(readOnly = true)
public class OverSeasProductService {
    @Autowired
    private TbQiNiuMapper tbQiNiuMapper;
    @Autowired
    private TbOverSeasProductDao tbOverSeasProductDao;
    @Autowired
    private TbAttachmentMapper tbAttachmentMapper;

    @Autowired
    private TbAgentProductMapper tbAgentProductMapper;
    @Autowired
    private TbProductAttributeDao tbProductAttributeDao;
    @Autowired
    private TbAgentProductDao tbAgentProductDao;

    @Autowired
    private TbCategoryDao TbCategoryDao;

    public Page<TbProduct> findProductByPage(Page<TbProduct> tbProductPage, TbProduct tbProduct) {
        tbProduct.setPage(tbProductPage);
        //商品管理list
        List list = tbOverSeasProductDao.findByPage(tbProduct);
        for(int i=0;i<list.size();i++){
            TbProduct tb=(TbProduct)list.get(i);
            TbShopProduct tbShopProduct=new TbShopProduct();
            tbShopProduct.setProductId(tb.getId());
            List<TbShopProduct> tshopProduct=tbOverSeasProductDao.selectTbshopproduct(tbShopProduct);
            tb.setTbshopProductList(tshopProduct);
        }
        //根据商品id得到属性
        tbProductPage.setList(list);
        return tbProductPage;
    }

    @Transactional(readOnly = false)
    public int saveOrUpdateProduct(TbProduct tbProduct, String storeNum, String alertStoreNum) {
        User user = UserUtils.getUser();
        //根据uid得到shop_id,如果没有给出提示，还没有店铺，如果有可以添加商品
        TbShop tbShop=tbOverSeasProductDao.selectShopByUid(user.getId());
        //更新时间
        int result = 0;
        //添加商品
        Date nowTime = new Date();
        tbProduct.setUpdateTime(nowTime);
        if(tbShop!=null){
            TbShopProduct tbShopProduct=new TbShopProduct();
            tbShopProduct.setShopId(tbShop.getId());
            tbShopProduct.setCreateTime(nowTime);
            tbShopProduct.setUpdateTime(nowTime);
            tbShopProduct.setStoreNum(0);
            //店铺存在商品存在，tb_shop_product存在，不存在
            if (null != tbProduct.getId() && !"".equals(tbProduct.getId())) {
                //更新时间
                tbProduct.setUpdateTime(nowTime);
                result = tbOverSeasProductDao.updateByPrimaryKeySelective(tbProduct);
                //判断该商品，在tb_shop_product中是否存在
                tbShopProduct.setProductId(tbProduct.getId());
                List<TbShopProduct> tshopProduct=tbOverSeasProductDao.selectTbshopproduct(tbShopProduct);
                if(tshopProduct.size()>0) {
                    tbShopProduct.setId(tshopProduct.get(0).getId());
                    //删除tb_shop_product中的商品
                    Integer shooplen = tbOverSeasProductDao.deleteShopProduct(tbShopProduct);
                }
            }else {
                //店铺存在商品不存在
                //保存商品信息
                tbProduct.setCreateTime(nowTime);
                tbProduct.setReserveFlag("2");
                result = tbOverSeasProductDao.insertSelective(tbProduct);
            }
            tbShopProduct.setProductId(tbProduct.getId());
            //添加tb_shop_product商品信息
            for(int i=0;i<tbProduct.getProductAttrGroup().size();i++){
                TbProductAttributeGroup tb=tbProduct.getProductAttrGroup().get(i);
                if(tb.getSku()!=null&&!tb.getSku().equals("")){
                    //属性
                    tbShopProduct.setColor(tb.getSku());
                    //货号
                    tbShopProduct.setProductSize(tb.getUnit());
                    //价格
                    tbShopProduct.setPrice(tb.getPrice());
                    tbOverSeasProductDao.insertTbshopProduct(tbShopProduct);
                }
            }
        }else{
            //该商铺不存在
            return 0;
        }
        return tbProduct.getId();
    }

    public List<TbAgentProduct> getTbAgentProduct(int productId) {
        User user = UserUtils.getUser();
        String userId = user.getId();
        List<TbAgentProduct> tbAgentProduct = tbAgentProductMapper.getAgentProductByProIdAndAgentId(productId, userId);
        return tbAgentProduct;
    }
    //根据条形码判断商品是否存在
    @Transactional(readOnly = false)
    public TbProduct selectProductBybarcode(String barcode){
        //根据条形码判断该商品是否存在，如果存在则修改，不存在新增
        return tbOverSeasProductDao.selectProductBybarcode(barcode);
    }
    //根据商品id判断商品是否存在tb_shop_product
    @Transactional(readOnly = false)
    public List<TbShopProduct> selectShopProductByProductId(Integer productId){
        TbShopProduct tbShopProduct=new TbShopProduct();
        tbShopProduct.setProductId(productId);
        List<TbShopProduct> list=tbOverSeasProductDao.selectTbshopproduct(tbShopProduct);
        //根据条形码判断该商品是否存在，如果存在则修改，不存在新增
        return list;
    }
    @Transactional(readOnly = false)
    public TbCategory getTbCategory(String id) {

        return TbCategoryDao.get(id);
    }


    public TbProduct get(Integer id) {
        return tbOverSeasProductDao.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = false)
    public void delete(TbProduct tbProduct) {
        tbProduct.setIsDelete(new Byte("1"));
        tbOverSeasProductDao.updateByPrimaryKey(tbProduct);
    }
    @Transactional(readOnly = false)
    public TbShopProduct selectTbshopProductById(Integer id){
        TbShop tbShop=tbOverSeasProductDao.selectShopByUid(UserUtils.getUser().getId());
        TbShopProduct tbShopProduct=new TbShopProduct();
        tbShopProduct.setShopId(tbShop.getId());
        tbShopProduct.setProductId(id);
        return tbOverSeasProductDao.selectTbshopproduct(tbShopProduct).get(0);
    }
    /**
     * 上传商品图片
     *
     * @param multiFileMap
     * @param request
     * @return
     */
    @Transactional(readOnly = false)
    public List<String> uploadMulFile(MultiValueMap<String, MultipartFile> multiFileMap, HttpServletRequest request) {
        List<String> urlList = new ArrayList<String>();
        TbQiNiuAccount tbQiNiuAccount = new TbQiNiuAccount();
        tbQiNiuAccount.setType("H5");
        TbQiNiuAccount account = tbQiNiuMapper.selectByType(tbQiNiuAccount);
        List<String> paths = new ArrayList<String>();
        for (String key : multiFileMap.keySet()) {
            List<MultipartFile> MultipartFiles = multiFileMap.get(key);
            for (MultipartFile file : MultipartFiles) {
                try {
                    String fileName = file.getOriginalFilename();
                    UUID uuid = UUID.randomUUID();
                    String uuidStr = uuid.toString();
                    int beginIndex = fileName.lastIndexOf(".");
                    String suffix = fileName.substring(beginIndex);
                    UploadDemo uploadDemo = new UploadDemo();
                    uploadDemo.setAccessKey(account.getAccessKey());
                    uploadDemo.setSecretKey(account.getSecretKey());
                    uploadDemo.setBucketName(account.getBucketName());
                    uploadDemo.setDomain(account.getDomain());

                    uploadDemo.uploadFile(uuidStr + suffix, file.getInputStream());

                    String downloadUrl = uploadDemo.getDownloadFileUrl(uuidStr + suffix);
                    //截取拼接字符串
                    String Url = downloadUrl.substring(0, downloadUrl.indexOf(suffix));
                    String url = Url + suffix;
                    urlList.add(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return urlList;
    }

    @Transactional(readOnly = false)
    public void insertProductImg(int id, List<String> uploadUrl) {

        //delete old pics
        List<TbAttachment> list = tbAttachmentMapper.selectByFkId(id);
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                this.tbAttachmentMapper.deleteByPrimaryKey(list.get(i).getId());
            }
        }

        if (uploadUrl == null || uploadUrl.size() == 0) {
            return;
        }

        //add new pics
        TbAttachment attachment = new TbAttachment();
        attachment.setFkId(id);
        attachment.setTbName("TbProduct");
        for (int i = 0; i < uploadUrl.size(); i++) {
            if (i == 0) {
                attachment.setIsMain("1");
                attachment.setImageUrl(uploadUrl.get(i));
                tbAttachmentMapper.insert(attachment);
            } else {
                attachment.setIsMain("0");
                attachment.setImageUrl(uploadUrl.get(i));
                tbAttachmentMapper.insert(attachment);
            }
        }
    }

}
